#include "ex06aa.cpp"
#include "pwext.hpp"
#include <stdio.h>

class malloc_arena
{
public:
	malloc_arena() :
		total_(0)
	{ 
		fprintf(stderr, "creating malloc_arena %p\n", this);
	}

	~malloc_arena()
	{
		fprintf(stderr, "destroying malloc_arena %p\n", this);
	}

	// just for show, count the bytes and return the pointer to itself
	void *get_block(size_t bytes)
	{
		total_ += bytes;
		fprintf(stderr, "malloc_arena %p: total %d\n", this, (int)total_);
		return this;
	}

	size_t total_;
};

// [[ex06ad]]
// DEBUG descr An object defined in an explicit context instead of the thread-specific data.
// its implementation is not important here
class malloc_arena; 

class our_malloc
{
public:
	void *malloc(size_t bytes)
	{
		return arena_.get_block(bytes);
	}

protected:
	malloc_arena arena_;
	// ... other definitions ...
};
// END

// DEBUG {
void otherfunc(our_malloc *malc)
{ }
void yetotherfunc(our_malloc *malc)
{ }
// DEBUG }

// [[ex06ae]]
// DEBUG descr An explicit context used instead of the thread-specific data.
void somefunc(our_malloc *malc)
{
	void *p = malc->malloc(100);
	// ...
	// pass the context to the nested function
	otherfunc(malc); 
	// ...
}

// DEBUG from
void run()
{
// DEBUG to
// ...
our_malloc *om = new our_malloc;
somefunc(om);
yetotherfunc(om);
// ...
delete om;
// ...
// DEBUG from
}
// END
